//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by mac on 15/11/28.
//  Copyright © 2015年 zsl. All rights reserved.
//

import UIKit
import AFNetworking


class UserAccountViewModel: NSObject {
    
     //mark:处理登录成功之后,停止网络请求
    var accounct: UserAccount?
    override init() {
        super.init()
        accounct = UserAccount.loadAccount()
    }
    
    //用户是否登录
    var userLogin: Bool{
        return accounct?.access_token != nil
    }
    var token: String?{
        return accounct?.access_token
    }
    var userName: String?{
        return accounct?.name
    }
    
    //请求用户token 获取授权
    func loadAccessToken(code:String, finshed: (error: NSError?) -> ()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求的参数parameters:
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
       
        print ("ccccc",parameters)
        
        let AFN = AFHTTPSessionManager()
        //添加反序列化类型
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            //拿到用户token之后,立即请求用户
            guard let dict = result as? [String: AnyObject] else{
                return
            }
            let account = UserAccount(dict: dict)
            
            self.loadUserInfo(account, finshed:finshed)
            }) { (_ , error ) -> Void in
                finshed(error: error)
                print(error)
        }
    }
    
    //private func loadUserInfo(token: String,uid: String){
    private func loadUserInfo(account:UserAccount,finshed: (error: NSError?) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //为了安全期间
        guard let access_token = account.access_token, userId = account.uid else{
           // SVProgressHUD.showErrorWithStatus("网络加载失败,请稍后再试")
            return
        }
        
        let paramters = ["access_token":access_token,"uid":userId]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: paramters, success: { (_, result) -> Void in
            
            //print (result)
            //转换数据类型的时候  as + ? 还是 ! 需要根据接受的数据类型是什么类型 来添加
            account.avatar_large = result["avatar_large"] as? String
            account.name = result["name"]as? String
            
            print(account)
            //保存用户信息
            account.saveAccount()
            finshed(error: nil)
            }) { (_, error) -> Void in
                
                finshed(error: error)
                
                print (error)
        }
        
        
    }

}
